#!/bin/bash

DIR=`dirname "$0"`


######
## Set up known config variables
######

echo ">>>"
echo ">>> Parsing Config File"
echo ">>>"

CONFIG="$DIR""/build_config"
if [ ! -f $CONFIG ]; then
    echo "Touching config file"
    touch "$CONFIG""/build_config"
fi

# Read all the config values into respective variables
while read line; do
    # Skip comments
    if [[ ${line:0:1} == "#" ]]; then
        continue
    fi
    
    CONFIG_ITEM=`echo "$line" | grep "="`
    
    if [[ ! "$CONFIG_ITEM" == "" ]]; then
        # Parse variable name and value from config item form name=value
        VAR_NAME=`echo "$CONFIG_ITEM" | sed 's_^\(.*\)=.*_\1_'`
        VAR_VALUE=`echo "$CONFIG_ITEM" | sed 's_^.*=\(.*\)_\1_'` 
        
        if [[ ! "$VAR_VALUE" == "" ]]; then
            eval "$VAR_NAME"="$VAR_VALUE"
        fi
    fi
done < "$CONFIG"


######
## Get other (non added config variables)
######

#todo




######
## MYSQL Setup
######

echo ">>>"
echo ">>> Setting up MYSQL database"
echo ">>>"

echo ";" | mysql --host="$MYSQL_LOCATION" --user="$MYSQL_USER" --password="$MYSQL_PASS" 2> /dev/null

if [[ $? == 1 ]]; then
    echo "Sorry, your database config is incorrect"
    exit 1
fi

echo "drop database $MYSQL_DB;" | mysql --host="$MYSQL_LOCATION" --user="$MYSQL_USER" --password="$MYSQL_PASS" 2> /dev/null
echo "create database $MYSQL_DB;" | mysql --host="$MYSQL_LOCATION" --user="$MYSQL_USER" --password="$MYSQL_PASS"
echo "source $DIR/create_tables.sql" | mysql --host="$MYSQL_LOCATION" --user="$MYSQL_USER" --password="$MYSQL_PASS" --database="$MYSQL_DB"
echo "source $DIR/insert_test_values.sql" | mysql --host="$MYSQL_LOCATION" --user="$MYSQL_USER" --password="$MYSQL_PASS" --database="$MYSQL_DB"

######
## Website copying
######

echo ">>>"
echo ">>> Copying website"
echo ">>>"

## Copy main files over (Must do as su to have this not fail...)
rsync -avzP --delete $DIR/../website/ $WWW_DIR/

## Set permissions (Must do as su to have this not fail...)
chmod -R 777 $WWW_DIR/app/tmp $WWW_DIR/app/webroot

## Copy htaccess
mv -f $WWW_DIR/.htaccess.default $WWW_DIR/.htaccess
mv -f $WWW_DIR/app/.htaccess.default $WWW_DIR/app/.htaccess
mv -f $WWW_DIR/app/webroot/.htaccess.default $WWW_DIR/app/webroot/.htaccess

## Create cubist_db_info.php
echo "<?php" > $WWW_DIR/../sfp_info.php
echo "define('cse403_user', "\'$MYSQL_USER\'");" >> $WWW_DIR/../sfp_info.php
echo "define('cse403_pass', "\'$MYSQL_PASS\'");" >> $WWW_DIR/../sfp_info.php
echo "define('cse403_salt', "\'$CAKE_SALT\'");" >> $WWW_DIR/../sfp_info.php
echo "define('cse403_seed', "\'$CAKE_SEED\'");" >> $WWW_DIR/../sfp_info.php
echo "define('cse403_dbloc', "\'$MYSQL_LOCATION\'");" >> $WWW_DIR/../sfp_info.php
echo "define('cse403_dbname', "\'$MYSQL_DB\'");" >> $WWW_DIR/../sfp_info.php
echo "define('cse403_dbtestname', "\'$MYSQL_DB"_test"\'");" >> $WWW_DIR/../sfp_info.php
echo "define('cse403_dbtest2name', "\'$MYSQL_DBTEST2"_test2"\'");" >> $WWW_DIR/../sfp_info.php
